//
//  XDErrotsCampViewController.m
//  XDEducation
//
//  Created by apple on 2017/4/18.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "XDErrotsCampViewController.h"
#import "XDErrorTopicCell.h"
#import "XDErrorTopicModel.h"
#import "XDErrorsStarWarModel.h"
#import "XDErrorHomeWorkModel.h"
#import "XDUnitCementSelectCourseViewController.h"
typedef enum : NSUInteger {
    MenuTypeReview = 1,     //复习巩固
    MenuTypeHomeWork,       //课外作业
    MenuTypeStarWar,        //全能星战
    MenuTypeTest,           //课前小测
    MenuTypeAnswerRecord,   //做题记录
    MenuTypeErrorsRanking,  //错题排行
    MenuTypePractice,       //强化练习
    MenuTypeCoach,          //线下辅导
} MenuType;


@interface XDErrotsCampViewController ()<UITableViewDelegate,UITableViewDataSource>



/** 菜单tableview */
@property (weak, nonatomic) IBOutlet UITableView *menuTableView;

/** 详情tableview */
@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** 菜单选项 */
@property(nonatomic,strong) NSArray *menuItemArr;

/** 详情tableview 数据源 */
@property(nonatomic,strong) NSMutableArray *dataListArr;

/** 日期数据源 */
@property(nonatomic,strong) NSArray *dateArr;

/** 当前选中的时间 */
@property(nonatomic,copy) NSString *selectedDate;

/** 当前的选中的菜单类型 */
@property(nonatomic,assign) MenuType menuType;

/** 判断详情cell是否为日期形式 */
@property(nonatomic,assign) NSInteger dateType;  // 1表示日期

@end

static NSString *errorTopicCellId = @"ErrorTopicCell";

@implementation XDErrotsCampViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"错题集中营";
    [self initTableView];
    
    self.dateType = 1;
    self.menuType =  1;
    [self getTimesRequestWithUrlAction:@"myresult.do?action=gettimesbyuid"];
}


-(void)initTableView{
    
    self.menuTableView.tableFooterView = [UIView new];
    self.tableView.tableFooterView = [UIView new];
    
}

#pragma mark - 懒加载

-(NSArray *)menuItemArr{
    if (!_menuItemArr) {
        _menuItemArr = [NSArray arrayWithObjects:
                          @"复习巩固",
                          @"课外作业",
                          @"全能星战",
                          @"课前小测",
                          @"做题记录",
                          @"错题排行",
                          @"强化练习",
                          @"线下辅导",
                          nil];
    }
    return _menuItemArr;
}


#pragma mark - tableview delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    if (tableView == self.menuTableView) {
         return 1;
    }
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    if (tableView == self.menuTableView) {
        return self.menuItemArr.count;
    }
    
    
    //详情tableview
    if(self.dateType == 1){     //日期类型
        
        return self.dateArr.count;
        
        
    }else{
        
        return self.dataListArr.count;
       
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.menuTableView) {
        
        return 44;
        
    }else{
        if(self.dateType == 1){
            
            return 44;
            
        }else{
        
            if (self.menuType == MenuTypeReview || self.menuType == MenuTypeHomeWork || self.menuType == MenuTypeStarWar ||self.menuType == MenuTypeTest) {
                
                return 90;
                
            }else{
                return 44;
            }
            
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.menuTableView) {
        
        static NSString *cellId = @"menu";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.text = self.menuItemArr[indexPath.row];
        
        //设置菜单cell第一行默认选中
        if (indexPath.row == 0) {
            [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:(UITableViewScrollPositionNone)];
            
        }
        return cell;
        
    }else{
        //内容栏tableview
        
        if (self.dateType == 1 ) {
            
            static NSString *cellId = @"date";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            }
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.text = self.dateArr[indexPath.row];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
           
        }else if (self.menuType == MenuTypePractice){   //强化练习
            
            static NSString *cellId = @"pratice";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            }
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.text = self.dataListArr[indexPath.row];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return cell;
        }
        else{
            if (self.menuType == MenuTypeReview || self.menuType == MenuTypeHomeWork || self.menuType == MenuTypeStarWar ||self.menuType == MenuTypeTest) {
                
                [tableView registerNib:[UINib nibWithNibName:@"XDErrorTopicCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:errorTopicCellId];
                XDErrorTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:errorTopicCellId];
                
                if (self.menuType == MenuTypeStarWar) {
                    
                    cell.startWarModel = self.dataListArr[indexPath.row];
                    
                } else if(self.menuType == MenuTypeHomeWork){
                    
                    cell.homeWorkModel = self.dataListArr[indexPath.row];
                    
                }else{
                    
                    cell.errorTopModel = self.dataListArr[indexPath.row];
                }
                return cell;
            }else{
            
                return nil;
            }
            
          
        }
    }
   
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(tableView == self.menuTableView){    
        //选中的菜单标题
        self.dateType = 1;
        self.menuType = indexPath.row + 1;
        

        if (self.menuType == MenuTypeReview) {
            
            [self getTimesRequestWithUrlAction:@"myresult.do?action=gettimesbyuid"];
            
        }else if(self.menuType == MenuTypeHomeWork  ||  self.menuType == MenuTypeTest){
            
            [self getTimesRequestWithUrlAction:@"exercise.do?action=getHomeworkTimesByUid"];
            
        }else if (self.menuType == MenuTypeStarWar){
            [self getTimesRequestWithUrlAction:@"exercise.do?action=getAllStrengthFire"];
            
        }else if(self.menuType == MenuTypePractice){    //强化练习
            //跳转到单元巩固
            self.dateArr = [NSArray arrayWithObjects:@"单元巩固",@"期中期末巩固", nil];
            [self.tableView reloadData];
        }
        else if (self.menuType == MenuTypeCoach){      //线下辅导
            [self openApp];
        }
        
    }else{
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        if(self.dateType == 1){     //日期点击
        
            if (self.menuType == MenuTypeReview) {  //复习巩固点击
                //选中的时间
                _selectedDate = self.dateArr[indexPath.row];
                //发送网络请求 刷新详情表
                [self getErrorsTopicListRequestWithAction:@"myresult.do?action=geterrorcountbytime"];
                
            }else if(self.menuType == MenuTypeHomeWork || self.menuType == MenuTypeTest){
                
                //选中的时间
                _selectedDate = self.dateArr[indexPath.row];
                //发送网络请求 刷新详情表
                [self getErrorsTopicListRequestWithAction:@"exercise.do?action=getErrorCountByTimeHw"];
                
            }else if (self.menuType == MenuTypeStarWar){
                
                //选中的时间
                _selectedDate = self.dateArr[indexPath.row];
                //发送网络请求 刷新详情表
                [self getErrorsTopicListRequestWithAction:@"myresult.do?action=getStrengthErrorCount"];
            }
            self.dateType = 0;
            
        }else{      //非日期cell点击
            
            if (self.menuType == MenuTypePractice) {    //强化练习 跳转单元巩固 和期中期末巩固
                if (indexPath.row == 0) {   //单元巩固
                    XDUnitCementSelectCourseViewController *vc = [[XDUnitCementSelectCourseViewController alloc]init];
                    vc.title = @"单元巩固";
                    vc.selectCourseType = SelectCourseTypeUnitCement;
                    [self.navigationController pushViewController:vc animated:YES];
                }else{      //期中期末巩固
                    XDUnitCementSelectCourseViewController *vc = [[XDUnitCementSelectCourseViewController alloc]init];
                    vc.title = @"期中期末巩固";
                    vc.selectCourseType = SelectCourseTypeTermCement;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                
            }
        }
    }

}


#pragma mark - 网络请求

/** 请求日期数据 */
-(void)getTimesRequestWithUrlAction:(NSString *)action{
    self.dataListArr = nil;

    NSString *url = BaseURL(action);
    NSDictionary *dict = @{@"uid":[AccountTool shareAccountTool].currentAccount.uid};
    
    if (self.menuType == MenuTypeTest) {
        dict =  @{@"uid":[AccountTool shareAccountTool].currentAccount.uid,@"type":@2}; //课前小测 type = 2
    }
    
    [MBProgressHUD showHUD];
    [XDHttpTool get:url authCode:[AccountTool shareAccountTool].currentAccount.authCode params:dict success:^(id responseObj) {
        [MBProgressHUD hideHUD];
        self.dateArr = responseObj;
        [self.tableView reloadData];
        if (self.dateArr.count == 0) {
            [MBProgressHUD showError:@"没有对应数据"];
        }
        
    } failure:^(NSError *error) {
        [MBProgressHUD showError:XDNetWorkError];
        [MBProgressHUD hideHUD];
        NSLog(@"%@",error);
    }];
    
}


/** 获取错题列表 */
-(void)getErrorsTopicListRequestWithAction:(NSString *)action{
   self.dataListArr = nil;
    NSDictionary *dict = @{@"uid":[AccountTool shareAccountTool].currentAccount.uid,
                          @"querytime":_selectedDate};
    
    if(self.menuType == MenuTypeTest){  //课前小测
        dict = @{@"uid":[AccountTool shareAccountTool].currentAccount.uid,
                 @"querytime":_selectedDate,
                 @"type":@2};  //课前小测 类型默认为2
    }
    
    NSString *url = BaseURL(action);

    [MBProgressHUD showHUD];
    [XDHttpTool get:url authCode:[AccountTool shareAccountTool].currentAccount.authCode params:dict success:^(id responseObj) {
        
        [MBProgressHUD hideHUD];
        //NSLog(@"%@",responseObj);
        NSArray *dictArr = responseObj;
        
        if(self.menuType == MenuTypeStarWar){   //全能星战
            
            dictArr = [responseObj objectForKey:@"t"];
            self.dataListArr =  [XDErrorsStarWarModel mj_objectArrayWithKeyValuesArray:dictArr];
            
        }else if(self.menuType == MenuTypeHomeWork){
            
            self.dataListArr =[XDErrorHomeWorkModel mj_objectArrayWithKeyValuesArray:dictArr];
            
        }else{
            self.dataListArr = [XDErrorTopicModel mj_objectArrayWithKeyValuesArray:dictArr];
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD hideHUD];
        NSLog(@"%@",error);
    }];

    
}



/**
 打开优学汇
 */
-(void)openApp{
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"bestLearning123://"]];
    
    //1 获取对应程序的URL
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"bestLearning123://"]];
    
    
    //2 判断手机中是否安装了对应的应用程序
    
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        
        //3 打开应用程序
        
        [[UIApplication sharedApplication] openURL:url];
        
        
    }else{
        
        UIAlertController *alter = [UIAlertController alertControllerWithTitle:nil message:@"您还未安装优学汇App,请前往AppStore下载" preferredStyle:UIAlertControllerStyleAlert];
        
        [alter addAction:[UIAlertAction actionWithTitle:@"立即下载" style: UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            
            NSString *str = [NSString stringWithFormat:@"https://itunes.apple.com/cn/app/id1211706475?mt=8"];
            NSURL * url = [NSURL URLWithString:str];
            
            if ([[UIApplication sharedApplication] canOpenURL:url])
            {
                [[UIApplication sharedApplication] openURL:url];
            }
            else
            {
                NSLog(@"can not open");
            }
            
        }]];
        
        [alter addAction:[UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
        [self presentViewController:alter animated:YES completion:nil];
        
        
    }
}

@end
